<script setup lang="ts">
import { computed, onMounted, ref, watch } from 'vue'
import router from '@/router'
import { getCategoryTree } from '@/api/category'
import { findSpu } from '@/api/product'
import {useProductStore} from '@/stores/modudels/product2'

const productStore = useProductStore()
const querySpuList = productStore.querySpuList
const formData = productStore.formData
console.log('setUp: ', productStore.formData)

onMounted(async () => {
  //获取分类数据
  const  result  = await getCategoryTree()
  console.log(result)
  if (result.code === 200) {
      categoryData.value = result.data
  }
})

const categoryData = ref([])
const selectCategory = ref([])

//选择分类
const handleCategoryChange = (value) => {
  selectCategory.value = value
  console.log('selectCategory', selectCategory.value)
}

// const categoryId = computed(() => {
//   if (selectCategory.value.length === 3) {
//     return selectCategory.value[selectCategory.value.length - 1]
//   }
//   return null
// })
const tableData = ref([])
watch(selectCategory, async () => {
  querySpuList.value=[]
  if (selectCategory.value.length === 3) {
  //加载对应分类的SPU
    const spuList = await findSpu(selectCategory.value[selectCategory.value.length - 1])
    console.log(spuList)
    if (spuList.code === 200) {
      tableData.value = spuList.data.data
      //将查询的数据存到store中,方便编辑使用
      querySpuList.value = spuList.data.data
    }
  }
},{deep:true})
//跳转去添加SPU页面
const addSpu = () => {
  router.push({
    // path:`/product/addSpu3/${selectCategory.value[selectCategory.value.length - 1]}`,
    path:`/product/addSpu3`,
    query: {
      catid: selectCategory.value[selectCategory.value.length - 1]
    }
  })
}
//编辑spu
const editSpu = (row) => {
  //将数据存储到store中
  productStore.formData = row
  console.log('editSpu: ', productStore.formData)
  router.push({
    path: '/product/addSpu3',
    query: {
      id: row.id
    }
  })
}
</script>

<template>
  <div class="spu_coontenLayout">
    <div class="selectCategory">
      <el-cascader @change="handleCategoryChange"
      :options="categoryData"
      :props="{
        label:'name',
        value:'id',
        children:'child'
      }"></el-cascader>
    </div>
    <el-button @click="addSpu">添加SPU</el-button>
    <el-button>批量删除</el-button>
    <el-table  :data="tableData" style="width: 100%">
      <el-table-column prop="id" label="序号" width="80" />
      <el-table-column prop="title" label="标题" width="280" />
      <el-table-column prop="subTitle" label="副标题" />
      <el-table-column label="操作" width="200">
        <template #default="scope">
          <el-button @click="editSpu(scope.row)">编辑</el-button>
          <el-button>预览</el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<style scoped lang="scss"></style>
